import axios from "axios";
import {useUserLoginStore} from "@/stores/AccountLogin.js";
import {ElMessage} from "element-plus";


const loginStore = useUserLoginStore();

//创建请求配置
const service = axios.create({
    baseURL: "http://localhost:8800"
});

//请求拦截器
service.interceptors.request.use(
    (config) => {
        const jwtToken = loginStore.getJToken;

        if (jwtToken != null)
            config.headers['jToken'] = jwtToken;

        return config;
    },
    (error) => {
        console.log("--请求错误");
        Promise.reject(error).then();
    }
);

//响应拦截器
service.interceptors.response.use(
    (response) => {
        if (response.status !== 200) {
            console.log(`--响应失败：响应状态码【${response.status}】`);
            if (response.status === 401) {
                ElMessage({
                    message:'你还未登录，请登录',
                    type: "error",
                });
            }
            return;
        }
        return response.data;
    },
    (error) => {
        console.log(`响应错误：${error.toString()}`);
        return Promise.reject(error);
    }
);

//导出默认
export default service;

